package com.xumt.hwHMSdemo;

import androidx.annotation.RequiresPermission;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.huawei.hms.maps.CameraUpdateFactory;
import com.huawei.hms.maps.HuaweiMap;
import com.huawei.hms.maps.MapFragment;
import com.huawei.hms.maps.OnMapReadyCallback;
import com.huawei.hms.maps.SupportMapFragment;
import com.huawei.hms.maps.model.LatLng;
import com.huawei.hms.maps.model.Marker;
import com.huawei.hms.maps.model.MarkerOptions;
import com.huawei.hms.site.api.SearchResultListener;
import com.huawei.hms.site.api.SearchService;
import com.huawei.hms.site.api.SearchServiceFactory;
import com.huawei.hms.site.api.model.DetailSearchRequest;
import com.huawei.hms.site.api.model.DetailSearchResponse;
import com.huawei.hms.site.api.model.NearbySearchRequest;
import com.huawei.hms.site.api.model.SearchStatus;
import com.huawei.hms.site.api.model.Site;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class Detailed extends AppCompatActivity implements OnMapReadyCallback {
    private String key;
    private SearchService searchService;
    public static final String storemessage="com.demo.myfirstdemo.storemessage";
    private static final String TAG = "MapFragmentDemoActivity";
    public String storeaddress;
    public String storename;
    private HuaweiMap hMap;
    private Marker mMarker;
    private SupportMapFragment SupportMapFragment;
    public static final String myLongitude="com.demo.myfirstdemo.longitude1";
    public static final String myLititude="com.demo.myfirstdemo.lititude1";
    public Double myweidu;
    public Double myjingdu;
    private Double storeweidu;
    private Double storejingdu;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detailed);
        Intent intent = getIntent();
        String storeid = intent.getExtras().getString(storemessage);
        myjingdu = intent.getExtras().getDouble(myLongitude);
        myweidu = intent.getExtras().getDouble(myLititude);
        try {
            key= URLEncoder.encode("CgB6e3x9W985/nvaN5rd75cS5n7LEHs5wnWoEpG2sU21mBQZu4sryiiENsvarFzfa5zHvydkQpFF6cczRzbSNai5", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
// 创建SearchService实例
        searchService = SearchServiceFactory.create(this, key);
        // 创建请求体
        //   NearbySearchRequest request = new NearbySearchRequest();
        DetailSearchRequest request1 = new DetailSearchRequest();
        request1.setSiteId(storeid);
        request1.setLanguage("zn");
        request1.setChildren(false);
// 创建搜索结果侦听器
        SearchResultListener<DetailSearchResponse> resultListener1 = new SearchResultListener<DetailSearchResponse>() {
            // 正常结果返回
            @Override
            public void onSearchResult(DetailSearchResponse result) {
                Site site;
                if (result == null || (site = result.getSite()) == null) {
                    return;
                }
                Log.i("TAG", String.format("siteId: '%s', name: %s,address:%s\r\n", site.getSiteId(), site.getName(),site.getFormatAddress()));
//                Log.i("TAG", String.format("adress: '%s', place: %s,poi:%s\r\n", site.getAddress(), site.getViewport(),site.getPoi()));
                Log.i("TAG", String.format(" weizhi: %s,%s\r\n", site.getLocation().getLat(), site.getLocation().getLng()));
                storejingdu=site.getLocation().getLng();
                storeweidu=site.getLocation().getLat();
                TextView thisname=findViewById(R.id.storename);
                thisname.setText( "商店名称："+site.getName());
                TextView thisaddress=findViewById(R.id.storeadress);
                thisaddress.setText("商店地址："+site.getFormatAddress());
                storename=site.getName();
                storeaddress=site.getFormatAddress();
            }
            // 异常结果返回
            @Override
            public void onSearchError(SearchStatus status) {
                Log.i("TAG", "Error : " + status.getErrorCode() + " " + status.getErrorMessage());
            }
        };
// 调用地点详情接口
        searchService.detailSearch(request1, resultListener1);
        SupportMapFragment = (SupportMapFragment)  getSupportFragmentManager().findFragmentById(R.id.SupportMapFragment);
        SupportMapFragment.getMapAsync(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Log.i(TAG, "sdk >= 23 M");
            // 检查您的应用是否具有给定的权限，以及该权限对应的App Ops是否被允许
            if (ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // 请求授予此应用程序的权限
                String[] strings =
                        {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
                // 请求授予权限
                ActivityCompat.requestPermissions(this, strings, 1);
            }
        }
    }

    //    @RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})
    @SuppressLint("SupportAnnotationUsage")
    @RequiresPermission(allOf = {Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission. ACCESS_WIFI_STATE})
    @Override
    public void onMapReady(HuaweiMap huaweiMap) {
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(2000);
                    Log.d(TAG, "onMapReady: ");
                    hMap = huaweiMap;
                    hMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(myweidu,myjingdu), 10));
                    mMarker = hMap.addMarker(new MarkerOptions()
                            .position(new LatLng(storeweidu, storejingdu))
                            .title(storename)
                            .snippet(storeaddress));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            }
        }.start();

    }


//    Log.d(TAG, "onMapReady: ");
//        hMap = huaweiMap;
//        hMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(myweidu, myjingdu), 10));
//    mMarker = hMap.addMarker(new MarkerOptions()
//            .position(new LatLng(48.893478, 2.334595))
//            .title(storename)
//            .snippet(storeaddress));
//        hMap.setMyLocationEnabled(true);
//        // 启用我的位置按钮
//        hMap.getUiSettings().setMyLocationButtonEnabled(true);
}
//    public void addMarker(View view) {
//        if (null != mMarker) {
//            mMarker.remove();
//        }
//        MarkerOptions options = new MarkerOptions()
//                .position(new LatLng(48.893478, 2.334595))
//                .title("Hello Huawei Map")
//                .snippet("This is a snippet!编辑");
//        mMarker = hMap.addMarker(options);
//    }